/////////////////////////////////  Includes  / Defines ////////////////////////
#include "stdafx.h"
#include "MemoryMap.h"
#include <winioctl.h>


static int nCountCMemMapFile = 0;

///////////////////////////////// Implementation //////////////////////////////

CMemoryMap::CMemoryMap()
{
	m_hMemoryMap = NULL;
	m_lpMemoryMapPtr = NULL;
	m_bAutoRelease = TRUE;

	nCountCMemMapFile++;
}
CMemoryMap::~CMemoryMap()
{
	if(m_bAutoRelease)
		Release();
	nCountCMemMapFile--;
}

CMemoryMap::CMemoryMap(CString csMapKey, DWORD dwMaxSize,BOOL bAutoRelease  /*=TRUE*/)
{
	VERIFY(Create( csMapKey,  dwMaxSize, bAutoRelease  /*=TRUE*/));
}

HANDLE CMemoryMap::Create(CString csMapKey, DWORD dwMaxSize,BOOL bAutoRelease  /*=TRUE*/)
{
	m_dwMaxSize  = dwMaxSize;
	m_csMapKey   = _CreateMappingName(csMapKey);
	m_bAutoRelease = bAutoRelease;
	m_hMemoryMap = ::CreateFileMapping(INVALID_HANDLE_VALUE ,NULL,PAGE_READWRITE,0, m_dwMaxSize,m_csMapKey);
	if (m_hMemoryMap == NULL)
	{
		ASSERT(0);
		return NULL;
	}
	return m_hMemoryMap;
}

HANDLE CMemoryMap::Open(CString csMapKey)
{
	m_csMapKey = csMapKey;
	m_hMemoryMap = OpenFileMapping(FILE_MAP_ALL_ACCESS,	0, m_csMapKey);
	if (m_hMemoryMap == NULL) 
	{
		ASSERT(0);
		return NULL;
	}

	return m_hMemoryMap;
}

BOOL CMemoryMap::Flush()
{   
	if (!m_hMemoryMap)
		return FALSE;
	
	ASSERT(m_lpMemoryMapPtr);
	return FlushViewOfFile(m_lpMemoryMapPtr, 0);
}

void CMemoryMap::Release()
{
	Flush();

	if (!m_hMemoryMap)
		return;

	VERIFY(	UnmapViewOfFile(m_lpMemoryMapPtr) );
	VERIFY( CloseHandle(m_hMemoryMap) );

	m_lpMemoryMapPtr = NULL;
	m_hMemoryMap = NULL;
	m_csMapKey.Empty();
}
//private
CString& CMemoryMap::_CreateMappingName(CString& csMapKey)
{
	csMapKey.Replace(_T('\\') , _T('_'));
	csMapKey.MakeUpper();
	TRACE(_T("MemoryMap Key : %s\n"),csMapKey);
	return csMapKey;
}

//get
CString CMemoryMap::GetMapKey()
{
	return m_csMapKey; 
}
LPVOID CMemoryMap::GetMemoryMapPtr()
{
	ASSERT(!m_csMapKey.IsEmpty());
	ASSERT(m_hMemoryMap);

	m_lpMemoryMapPtr = MapViewOfFile(m_hMemoryMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	ASSERT(m_lpMemoryMapPtr);
	return m_lpMemoryMapPtr;
}
